package com.hjwoo.app.net;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import com.hjwoo.app.R;
import com.hjwoo.app.been.FailureResultObject;
import com.hjwoo.app.common.LoanApplication;
import com.hjwoo.app.utils.JsonParser;
import com.hjwoo.app.utils.LoanAccessTokenIdKeeper;
import com.hjwoo.app.utils.LoanLog;
import com.hjwoo.app.utils.LoanToast;
import com.hjwoo.app.utils.Utils;
import com.hjwoo.app.views.MainActivity;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;
import org.xutils.x;

/**
 * Created by yangchuan on 2016/5/9.
 */
public class HttpTool {

    public static Callback.Cancelable cancelable;

    //重载post
    public static void RequestPost(final org.xutils.http.RequestParams params, final String tag, final RequestListener requestlistener, final Context context) {

        //检查网络是否链接
        if (!Utils.isNetworkAvailable()) {
            Toast.makeText(LoanApplication.getInstance(), R.string.no_network_connection_toast, Toast.LENGTH_SHORT).show();
            return;
        }
        params.addHeader("Content-Type", "application/json");
        params.setAsJsonContent(true);
        final NetWaitBox waitBox;
        if (context != null) {
            waitBox = new NetWaitBox(context, R.style.loading_dialog);
            waitBox.show();
        } else {
            waitBox = null;
        }
//        ProgressDialogHelper.getProgressDialogHelper().creatProgress(context);
        cancelable = x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                LoanLog.e("请求成功，返回值为", "sss:" + result);
                LoanLog.e("请求成功，请求参数", params.toString());
                if (context != null) {
                    waitBox.dismiss();
                }
                requestlistener.requestSuccess(tag, result);
//                ProgressDialogHelper.getProgressDialogHelper().dismissDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                HttpException httpEx1 = (HttpException) ex;
//                LoanLog.e("请求错误", "错误：" + httpEx1.getCode() + ";getErrorCode:" + httpEx1.getErrorCode() + ";getResult:" + httpEx1.getResult() + ";getMessage:" + httpEx1.getMessage() + isOnCallback);

                if (ex instanceof HttpException) { // 错误
                    HttpException httpEx = (HttpException) ex;
                    LoanLog.e("请求成功，请求参数", params.toString());
                    LoanLog.e("请求失败，返回值为", httpEx.getResult());

                    //获取错误码
                    int responseCode = httpEx.getCode();
                    //获取信息
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    LoanLog.e("httputilsresponseCode", "" + responseCode + "; responseMsg:" + responseMsg + "; errorResult:" + errorResult);

                    FailureResultObject failureResultObject = JsonParser.getJsonParser().parserJsonToObj(errorResult, FailureResultObject.class);

                    if (failureResultObject.getErrorCode().equals("4400")) {
                        LoanToast.showToastShort(failureResultObject.getErrorMessage(), LoanApplication.getInstance());
                        LoanAccessTokenIdKeeper.clear(MainActivity.instance);
//                        LoanLog.e("http","id:"+LoanAccessTokenIdKeeper.readAccessToken(MainActivity.instance).getAppSessionId());
//                        UserCenterFragment userCenterFragment = new UserCenterFragment();
//                        userCenterFragment.refreshLoginstatus();
//                        //请登录
//                        MainActivity.currIndex = 3;
//                        MainActivity.showFragment();
//                        MainActivity.group.check(R.id.main_footbar_user);
                        //关掉所有界面
//                        AppManager.getAppManager().finishAllActivity();
                    }
//                LoanLog.e("请求失败1，请求参数", params.toString() + ex.getMessage());
//                    ProgressDialogHelper.getProgressDialogHelper().dismissDialog();
                    requestlistener.requestError(errorResult);
                } else {
                    LoanToast.showToastLong("网络超时,请稍后再试", context);
//                        java.net.SocketTimeoutException: Read timed out
//                        if (ex.toString().equals("java.net.SocketTimeoutException: Read timed out")){
//                        }
//                        LoanLog.e("err",ex.getMessage()+"dd"+ ex.getCause()+"dd"+ex.getCause()+"dd" +"dd" + ex.toString());
                }

                if (context != null) {
                    waitBox.dismiss();
                }
            }

            @Override
            public void onFinished() {
                LoanLog.e("请求完成", "请求完成");
                if (context != null) {
                    waitBox.dismiss();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LoanLog.e("请求中断", "请求中断");
                if (context != null) {
                    waitBox.dismiss();
                }
            }
        });


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (context != null) {

                    if (waitBox.isShowing()) {
                        Toast.makeText(context, "网络异常，请稍后再试！", Toast.LENGTH_SHORT).show();
                        requestlistener.requestSuccess("delayed", "网络异常，请稍后再试");
                        waitBox.dismiss();
                        //取消请求
                        HttpTool.cancelable.cancel();

                    }
                }
            }
        }, 30000);


    }


}
